package com.tonghe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tonghe.constants.SystemConstants;
import com.tonghe.domain.entity.LoginUser;
import com.tonghe.domain.entity.User;
import com.tonghe.mapper.MenuMapper;
import com.tonghe.mapper.UserMapper;
import com.tonghe.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @Date:2022/2/21- 02- 21- 10:26
 * @author: tonghe
 **/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    /**
    * @description:
    * @param： [username]
    * @return： org.springframework.security.core.userdetails.UserDetails
    * @author: TongHe
    * @date: 2022/3/17 17:56
    */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, username);
        queryWrapper.eq(User::getStatus,SystemConstants.NORMAL);
        User user = userMapper.selectOne(queryWrapper);
        // 判断是否查到用户，若未查到，抛出异常
        if(Objects.isNull(user)){
            throw new RuntimeException("用户不存在");
        }
        if(SystemConstants.ADMIN.equals(user.getType())){
            List<String> perms = menuMapper.selectPermsByUserId(user.getId());
            return new LoginUser(user,perms);
        }
        return new LoginUser(user,null);
    }
}
